package com.luckyframe.project.jmeter.execution.sum;


import org.apache.jmeter.control.TransactionController;
import org.apache.jmeter.report.core.Sample;
import org.apache.jmeter.report.core.SampleMetadata;
import org.apache.jmeter.reporters.Summariser;
import org.apache.jmeter.samplers.SampleEvent;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jmeter.samplers.SampleSaveConfiguration;
import org.apache.jmeter.save.CSVSaveService;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;


/**
 * summariser across whole  plan
 */
public class PlanResultSummariser extends Summariser {

    private long row=0;

    private BlockingQueue<Sample> samples;

    private SampleMetadata sampleMetadata = new SampleMetadata(
            SampleSaveConfiguration.staticConfig());

    /**
     * Constructor for use during startup (intended for non-GUI use)
     *
     * @param name of summariser
     */
    public PlanResultSummariser(String name,BlockingQueue<Sample> samples) {
        super();
        setName(name);
        this.samples=samples;
    }


    /**
     * Accumulates the sample in two SampleResult objects - one for running
     * totals, and the other for deltas.
     *
     */
    @Override
    @SuppressWarnings("SynchronizeOnNonFinalField")
    public void sampleOccurred(SampleEvent e) {

        SampleResult s = e.getResult();

        if( TransactionController.isFromTransactionController(s)) {
            return;
        }


        String delimitedResult = CSVSaveService.resultToDelimitedString(e);
        String[] data = delimitedResult.split(",");

        Sample  sample =new Sample (row++,sampleMetadata,data);
        samples.offer(sample);

    }




    /** {@inheritDoc} */
    @Override
    public void sampleStarted(SampleEvent e) {
        // not used
    }

    /** {@inheritDoc} */
    @Override
    public void sampleStopped(SampleEvent e) {
        // not used
    }


    public List<Sample> getSamples() {
        return new ArrayList<>(samples);
    }
}
